package com.odm.communitymanage.ui.activity

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.*
import com.jeremyliao.liveeventbus.LiveEventBus
import com.odm.communitymanage.R
import com.odm.communitymanage.base.BaseFragment
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.core.bean.MyActivityData
import com.odm.communitymanage.core.bean.NetCallBack
import com.odm.communitymanage.core.net.ApiService
import com.odm.communitymanage.ui.ImageDetailActivity
import com.odm.communitymanage.util.GlideUtils
import com.odm.communitymanage.widget.AvatarModeUtils
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_acitivity_detail.*
import rxhttp.wrapper.param.RxHttp

/**
 * @description: 活动详情页面
 * @author: ODM
 * @date: 2020/4/20
 */
class ActivityDetailFragment : BaseFragment() {

    //记录当前活动的 ID
    var activityId : Int = -1

    private var disposable : Disposable?= null

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        registerLiveEvent()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if(disposable?.isDisposed == false){
            disposable?.dispose()
        }
    }

    override fun initViews() {
        //结束活动的点击事件
        btnFinish_ActivityDetail.setOnClickListener {
            postFinishMyActivity()
        }

        //报名按钮的点击事件
        btnSignUp_ActivityDetail.setOnClickListener {
            postSignUpActivity()
        }
    }

    /**
     * 收到来自活动列表页面的加载详情的事件
     */
    private fun registerLiveEvent(){
        //首页活动列表
        LiveEventBus.get(Constants.EVENT_ACTIVITY_DETAIL , MyActivityData::class.java)
            .observeSticky(this  , object : Observer<MyActivityData> {
                override fun onChanged(t: MyActivityData?) {
                    loadActivityDetail(t)
//                    LogUtils.d("存储用户名 " + SPUtils.getInstance(Constants.SP_USER).getString(Constants.USER_NAME,""))
//                    LogUtils.d("活动发起者   " + t?.name)
                    //当活动发起人 != 我 且 当前状态为 进行中时，显示 我要报名 按钮
                    if(SPUtils.getInstance(Constants.SP_USER).getString(Constants.USER_NAME,"") != t?.name
                        && t?.status == 0){
                        btnSignUp_ActivityDetail.visibility  = View.VISIBLE
                    }
                }
            })
        //我的活动列表
        LiveEventBus.get(Constants.EVENT_MY_ACTIVITY_DETAIL , MyActivityData::class.java)
            .observeSticky(this  , object : Observer<MyActivityData> {
                override fun onChanged(t: MyActivityData?) {
                    loadActivityDetail(t)
                    //当活动发起人 == 我 且 当前状态为 进行中时，显示 结束活动 按钮
                    if(SPUtils.getInstance(Constants.SP_USER).getString(Constants.USER_NAME,"") == t?.name
                        && t?.status == 0){
                        btnFinish_ActivityDetail.visibility  = View.VISIBLE
                    }
                }
            })

    }


    private fun loadActivityDetail(data : MyActivityData ?){
        tvContactInfo_ActivityDetail?.text = data?.name
        tvTime_ActivityDetail?.text = data?.time
        tvTopic_ActivityDetail?.text = data?.topic
        tvMatters_ActivityDetail?.text = data?.matters
        tvDescription_ActivityDetail?.text = data?.description
        val imgUrls = data?.imgs?: mutableListOf()

        //保存当前活动的ID
        activityId = data?.id ?: -1
        //状态判断
        if(data?.status == 0){
            //进行中
            tvType_ActivityDetail?.text =  getString(R.string.ongoing)
            tvType_ActivityDetail?.setTextColor(ColorUtils.getColor(R.color.activity_doing))
            //显示报名按钮
//            btnSignUp_ActivityDetail?.visibility =  View.VISIBLE

        }else if(data?.status == 1){
            //已结束
            tvType_ActivityDetail?.text =  getString(R.string.over)
            tvType_ActivityDetail?.setTextColor(ColorUtils.getColor(R.color.activity_done))
            //隐藏报名按钮
//            btnSignUp_ActivityDetail?.visibility =  View.GONE
        }
        
        //图片加载
        var targetView : ImageView?= null
        for(url in imgUrls){
            if (ivPhoto_0_ActivityDetail?.visibility != View.VISIBLE) {
                targetView = ivPhoto_0_ActivityDetail
            } else if (ivPhoto_1_ActivityDetail?.visibility != View.VISIBLE) {
                targetView = ivPhoto_1_ActivityDetail
            }
            targetView?.apply {
                visibility = View.VISIBLE
                //加载图片
                GlideUtils
                    .getInstance()
                    .loadImageUrl(requireContext(),url ,targetView)
                //点击事件，跳转加载大图Activity
                setOnClickListener {
                    LiveEventBus
                        .get(Constants.IMAGE_URL)
                        .post(url)
                    ActivityUtils.startActivity(ImageDetailActivity::class.java)
                }
            }
        }
        if(ivPhoto_0_ActivityDetail?.visibility != View.VISIBLE){
            //无图片情况下，保底在第一张图片的位置显示一张 默认图
            GlideUtils.getInstance()
                .loadImageResourceId(requireContext(),
                    R.mipmap.ic_launcher ,
                    ivPhoto_0_ActivityDetail)
        }

        //加载头像
        setNameAvatar(data?.name ?: "无" , ivAvatar_ActivityDetail)

    }


    /**
     * post请求 结束当前我发布的活动
     */
    private fun postFinishMyActivity(){
        disposable = RxHttp.postJson(ApiService.FINISH_MY_ACTIVITY)
            .add("id",activityId)
            .asClass(NetCallBack::class.java)
            .subscribe({
                if(it.code== 1){
                    showSuccessSnack(getString(R.string.post_success))
                }else {
                    ToastUtils.showShort(it.message)
                }
            },{
                ToastUtils.showShort(it.message)
                it.printStackTrace()
            })
    }


    /**
     * post请求 报名当前活动
     */
    private fun postSignUpActivity(){
        disposable = RxHttp.postJson(ApiService.SIGN_UP_ACTIVITY)
            .add("id",activityId)
            .asClass(NetCallBack::class.java)
            .subscribe({
                if(it.code== 1){
                    showSuccessSnack(getString(R.string.post_success))
                    pop()
                }else {
                    ToastUtils.showShort(it.message)
                }
            },{
                ToastUtils.showShort(it.message)
                it.printStackTrace()
            })
    }

    
    




    override fun getLayoutId(): Int {
        return R.layout.fragment_acitivity_detail
    }
}